<template>
  <a-select v-model:value="val" :disabled="disabled" :mode="mode" :placeholder="placeholder" @change="onChange">
    <a-select-option v-for="(item, index) in dictOptions" :key="index">
      <span :class="[item.color ? 'colorText' : '']" :style="{ backgroundColor: `${item.color}` }">{{ item.text || item.label }}</span>
    </a-select-option>
  </a-select>
</template>
<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { getDictItems } from '/@/api/common/api';

  const emit = defineEmits(['update:value', 'change']);
  const props = defineProps({
    value: String,
    placeholder: String,
    disabled: Boolean,
    mode: {
      type: String,
      default: '',
    },
    code: String,
  });

  const val = ref<any>();

  const dictOptions = ref<any[]>([]);

  // 根据字典code查询字典项
  const loadDictOptions = async () => {
    const res = await getDictItems(props.code);
    if (res) {
      dictOptions.value = res.map((item) => ({ value: item.value, label: item.text, color: item.color }));
    } else {
      console.error('getDictItems error: : ', res);
      dictOptions.value = [];
    }
  };

  const onChange = (value: any) => {
    val.value = value
    emit('update:value', value);
    emit('change', value);
  };

  watch(
    () => props.value,
    (value) => {
      val.value = value || []
    },
    {immediate: true}
  )

  onMounted(() => {
    loadDictOptions();
  });
</script>
